package de.gameduell.framework.game.matching {
	import de.gameduell.framework.game.matching.ITile;
	import de.gameduell.framework.game.matching.TokenEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;	

	/**
	 * @author cbra
	 */
	public class GenTile extends EventDispatcher implements ITile {
		protected var _colIndex:int;
		protected var _rowIndex:int;	
		protected var _upNeighbour:ITile;
		protected var _downNeighbour:ITile;
		protected var _rightNeighbour:ITile;
		protected var _leftNeighbour:ITile;
		protected var _token:IToken;
		
		public function set token(aToken:IToken):void {
			 _token = aToken;
			
			 if(_token != null){
				 _token.addEventListener(TokenEvent.REMOVED, removeToken);
			 }		 
		}
		
		public function removeToken(event:Event = null):void{
			_token = null;
		}
		
		public function get token():IToken {
			return _token;
		}
		
		public function get colIndex():int{
			return _colIndex;
		}
		
		public function get rowIndex():int{
			return _rowIndex;
		}
		
		public function get upNeighbour():ITile {
			return _upNeighbour;
		}
		
		public function get downNeighbour():ITile {
			return _downNeighbour;
		}
		
		public function get rightNeighbour():ITile {
			return _rightNeighbour;
		}
		
		public function get leftNeighbour():ITile {
			return _leftNeighbour;
		}
		
		public function set upNeighbour(aNeighbour:ITile):void {
			 _upNeighbour = aNeighbour;
		}
		
		public function set downNeighbour(aNeighbour:ITile):void{
			 _downNeighbour = aNeighbour;
		}
		
		public function set rightNeighbour(aNeighbour:ITile):void{
			 _rightNeighbour = aNeighbour;
		}
		
		public function set leftNeighbour(aNeighbour:ITile):void{
			 _leftNeighbour = aNeighbour;
		}
		
		public function swapTokens(neighbour:GenTile):void{
			var neigbourToken:IToken = neighbour.token;
			neighbour.token = token;
			token = neigbourToken;
		}
		
		public function getNeighbours():Array{
			var neighbours:Array = new Array();
			if(_upNeighbour != null){
				neighbours.push(_upNeighbour);
			}
			if(_downNeighbour != null){
				neighbours.push(_downNeighbour);
			}
			if(_rightNeighbour != null){
				neighbours.push(_rightNeighbour);
			}
			if(_leftNeighbour != null){
				neighbours.push(_leftNeighbour);
			}
			return neighbours;
		}
		
		override public function toString():String{
			if(_token != null){
				return _token.color;
			}else{
				return null;
			}
//			return ""+_x+","+_y+" | "+ " token "+_token.color+" ";
		}
	}
}
